/**   
 * @Title: Cursor2Object.java 
 * @Package com.care.barsearch.util 
 * @Description: TODO
 * @author Evan 
 * @date Jun 18, 2012 10:04:28 PM 
 * @version V1.0   
 */
package com.evan.common.utils;

import java.lang.reflect.Field;

import org.json.JSONObject;

import android.database.Cursor;

public class Cursor2Object {

	private static String filterType = "boolean,Doctor,MyPatinenter";

	public static <T> T parseDataSource(Class<T> clazz, Cursor cursor) {
		T o = null;
		try {
			o = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				String fieldName = field.getName();
				if (!fieldName.equals("serialVersionUID")) {
					field.setAccessible(true);
					int index = cursor.getColumnIndex(fieldName);
					String type = field.getType().getName();
					if (index != -1 && !filterType.contains(type)) {
						try {
							field.set(o,
									type.equals("int") ? cursor.getInt(index)
											: cursor.getString(index));
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return o;
	}

	@SuppressWarnings({ "rawtypes" })
	public static JSONObject parseDataSourceJSONObject(Class clazz,
			Cursor cursor) {
		JSONObject object = new JSONObject();
		try {
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				String fieldName = field.getName();

				if (!fieldName.equals("serialVersionUID")) {
					int index = cursor.getColumnIndex(fieldName);
					String type = field.getType().getName();
					if (index != -1 && !filterType.contains(type)) {
						try {
							object.put(fieldName,
									type.equals("int") ? cursor.getInt(index)
											: cursor.getString(index));
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
}
